﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Models;
using BLL;
using Newtonsoft.Json;
using System.Threading.Tasks;
using YQFK.Models;
using Newtonsoft.Json.Linq;

namespace YQFK.api
{
    /// <summary>
    /// 
    /// </summary>
    public class RegisterController : ApiController
    {
        //// GET api/<controller>
        //public IEnumerable<string> Get()
        //{
        //    return new string[] { "value1", "value2" };
        //}


        /// <summary>
        /// 根据code获取openId并注册账号
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        //GET /api/Register/Get?code=code
        public HttpResponseMessage Get(string code)
        {
           string openId = new Helper.WxHelper().OpenID(code);
           // string openId = "oPr9a5N6cgVhZ2jB5VjfMzlMEUeI112";
            ResponeModel rm = new ResponeModel();
            if (string.IsNullOrEmpty(openId))
            {
                rm.code = -1;
                rm.count = 0;
                rm.data = null;
                rm.info = "获取openId失败";


            }
            else
            {

                LoginUserModel lum = new LoginUserBll().GetSingleDataByOpenId(openId);//根据openid判断是否已经存在数据
                if (lum == null || lum.User_id == null)//不存在，新增
                {
                    lum.IsManager = '0';
                    lum.OpenId = openId;
                    lum.UpdateTime = DateTime.Now;
                    lum.UserAccount = "yq" + lum.UpdateTime.ToString("yyyyMMddHHmmss") + new Random().Next(1001, 9999);
                    lum.UserPwd = "123456";
                   //lum.NickName = nickName;
                    bool b = new LoginUserBll().InsertSingleData(lum);//创建用户
                    if (b)
                    {
                        lum = new LoginUserBll().GetSingleDataByUserAccount(lum.UserAccount);
                        rm.code = 0;
                        rm.count = 1;
                        rm.data = new { userId = lum.User_id, userAccount = lum.UserAccount, openId = lum.OpenId.Trim(), departId = lum.DepartId, departName = lum.DepartName };
                        rm.info = "操作成功";

                    }
                    else
                    {

                        rm.code = -1;
                        rm.count = 0;
                        rm.data = null;
                        rm.info = "生成数据失败";

                    }
                }
                else//已存在
                {
                  //  new LoginUserBll().UpdateNickName(nickName, lum.User_id);
                    //如果用户已经存在，判断有单位id的单位是否存在，不存在就清空单位
                    if (string.IsNullOrEmpty(lum.DepartId))//不存在单位直接返回人员信息
                    {
                        rm.code = 0;
                        rm.count = 1;
                        rm.data = rm.data = new { userId = lum.User_id, userAccount = lum.UserAccount, openId = lum.OpenId.Trim(), departId = lum.DepartId, departName = lum.DepartName }; ;
                        rm.info = "操作成功";
                    }
                    else
                    {
                        //存在单位id判断单位是否存在，不存在就清空单位
                        int reslult = new LoginUserBll().SetDeaprt(lum.DepartId, lum.User_id);
                        if (reslult == 0)//单位不存在，清空单位
                        {
                            rm.code = 0;
                            rm.count = 1;
                            rm.data = rm.data = new { userId = lum.User_id, userAccount = lum.UserAccount, openId = lum.OpenId.Trim(), departId = "", departName = "" }; ;
                            rm.info = "操作成功";
                        }
                        else if (reslult == 1)//存在直接返回
                        {
                            rm.code = 0;
                            rm.count = 1;
                            rm.data = rm.data = new { userId = lum.User_id, userAccount = lum.UserAccount, openId = lum.OpenId.Trim(), departId = lum.DepartId, departName = lum.DepartName }; ;
                            rm.info = "操作成功";
                        }
                        else//设置单位为空出错
                        {
                            rm.code = -1;
                            rm.count = 1;
                            rm.data = rm.data = new { userId = lum.User_id, userAccount = lum.UserAccount, openId = lum.OpenId.Trim(), departId = lum.DepartId, departName = lum.DepartName }; ;
                            rm.info = "查询不到单位且用户单位信息清空失败";
                        }
                    }


                }

            }

            var result = JsonConvert.SerializeObject(rm);
            return new HttpResponseMessage { Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json") };

        }
        
        /// <summary>
        /// 完善信息
        /// </summary>
        /// <param name="jo"></param>
        /// <returns></returns>
        //POST api/Register/PostPerfectInfo
        public HttpResponseMessage PostPerfectInfo(JObject jo)
        {
            string jsonString = JsonConvert.SerializeObject(jo);
            var jsonParams = JsonConvert.DeserializeObject<dynamic>(jsonString);
            string nickName = jsonParams.nickName;
            string userId = jsonParams.userId;
            bool b = new LoginUserBll().UpdateNickName(nickName,userId);
            
            ResponeModel rm = new ResponeModel();
            
            rm.count = 0;
            rm.data = new object();
            
            if (b)
            {
                rm.code = 0;
                rm.info = "操作成功";
            }
            else
            {
                rm.code = -1;
                rm.info = "操作失败";
            }

            var result = JsonConvert.SerializeObject(rm);
            return new HttpResponseMessage { Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json") };
        }

        /// <summary>
        /// 根据当前userId设置当前用户是否是管理员
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="isManager"></param>
        /// <returns></returns>
        //GET /api/Register/GetSetManager?userId=userId&isManager=isManager
        public HttpResponseMessage GetSetManager(string userId, string isManager)
        {
            ResponeModel rm = new ResponeModel();
            bool b = new LoginUserBll().UpdateManager(userId, isManager);
            rm.count = 0;
            rm.data = new object();
            if (b)
            {
                rm.code = 0;
                rm.info = "操作成功";
            }
            else
            {
                rm.code = -1;
                rm.info = "操作失败";
            }
            var result = JsonConvert.SerializeObject(rm);
            return new HttpResponseMessage { Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json") };
        }

        /// <summary>
        /// 根据userId和departCode设置用户单位
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <param name="departCode">单位code</param>
        /// <returns></returns>
        //GET  api/Register/GetDepartInfoByCode?userId=userId&departCode=departCode
        public HttpResponseMessage GetDepartInfoByCode(string userId, string departCode)
        {
            ResponeModel rm = new ResponeModel();
            string[] strArr = new LoginUserBll().SetManageByCode(departCode, userId);

            rm.count = 0;
            rm.data = new object();
            if (strArr[0] == "0")
            {
                rm.code = 0;
                rm.info = "操作成功";
                rm.data = new { departId = strArr[1], departName = strArr[2] };
            }
            else
            {
                rm.code = int.Parse(strArr[0]);
                if (strArr[0] == "-1")
                {
                    rm.info = "操作失败";
                }
                else
                {
                    rm.info = "单位码不正确";
                }


            }
            var result = JsonConvert.SerializeObject(rm);
            return new HttpResponseMessage { Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json") };
        }

        /// <summary>
        /// 获取所有的账号信息
        /// </summary>
        /// <param name="nc"></param>
        /// <returns></returns>
        //GET api/Register/GetAllLUS
        public HttpResponseMessage GetAllLUS(string nc)
        {
            List<LoginUserModel> lm = new LoginUserBll().GetDataList();
            var result = JsonConvert.SerializeObject(lm);
            return new HttpResponseMessage { Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json") };
        }

        /// <summary>
        /// 根据userNo获取单挑数据
        /// </summary>
        /// <param name="userNo"></param>
        /// <returns></returns>
        public HttpResponseMessage GetSingleDataByUserNo(string userNo)
        {
            ResponeModel rm = new ResponeModel();
            LoginUserModel lum = new LoginUserBll().GetSingleDataByUserNo(userNo);
            rm.code = 0;
            rm.count = 1;
            rm.data = lum;
            rm.info = "操作成功";
            var result = JsonConvert.SerializeObject(rm);
            return new HttpResponseMessage { Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json") };
        }

        /// <summary>
        /// 根据user_id删除单条数据
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        //GET api/Register/GetDelData?user_id=user_id
        public HttpResponseMessage GetDelData(string user_id)
        {
            ResponeModel rm = new ResponeModel();
            bool b = new LoginUserBll().DelSingleDataById(user_id);
            if (b)
            {
                rm.code = 1;
                rm.count = 0;
                rm.data = new object();
                rm.info = "操作成功";
            }
            else
            {
                rm.code = 1;
                rm.count = 0;
                rm.data = new object();
                rm.info = "操作失败";
            }
            var result = JsonConvert.SerializeObject(rm);
            return new HttpResponseMessage { Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json") };
        }

        /// <summary>
        /// 根据用户账号获取判断当前用户是不是管理员
        /// </summary>
        /// <param name="userNo"></param>
        /// <returns></returns>
        //GET api/Register/GetIsManager?userNo=userNo
        public HttpResponseMessage GetIsManager(string userNo)
        {
            ResponeModel rm = new ResponeModel();

            bool b = new LoginUserBll().IsManager(userNo);
            if (b)
            {
                rm.code = 1;
                rm.count = 0;
                rm.data = new object();
                rm.info = "操作成功";
            }
            else
            {
                rm.code = 0;
                rm.count = 0;
                rm.data = new object();
                rm.info = "操作成功";
            }
            var result = JsonConvert.SerializeObject(rm);
            return new HttpResponseMessage { Content = new StringContent(result, System.Text.Encoding.UTF8, "application/json") };
            //}
        }

        // POST api/<controller>
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }
}